/*
 * Project it.battlehorse.rcp.tools.actors.sampledb
 * Created on Dec 2, 2005
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * A copy of the LGPL is available also at
 * http://www.gnu.org/copyleft/lesser.html
 * 
 */ 
package it.battlehorse.rcp.tools.actors.sampledb;

import it.battlehorse.rcp.sl.annot.Injected;
import it.battlehorse.rcp.sl.annot.Serviceable;
import it.battlehorse.rcp.tools.actors.IActorRunnable;
import it.battlehorse.rcp.tools.commons.actors.IActorExecutionStatus;
import it.battlehorse.rcp.tools.dbbase.DatasourceConfig;
import it.battlehorse.rcp.tools.dbbase.IDbManager;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.eclipse.core.runtime.IProgressMonitor;

/**
 * A class which perform the job defined by this actor and executes the user query against the
 * selected datasource.
 * 
 * @author battlehorse
 * @since Dec 2, 2005
 */
@Serviceable
public class SampleDbJob implements IActorRunnable {
	
	/* a logger */
	private Log log;
	
	/* a db manager */
	private IDbManager manager;
	
	/* The query to execute */
	private String query;
	
	/* The datasource to use */
	private DatasourceConfig cfg;
	
	/* The number of returned rows */
	private int rowCount;
	
	/* The error flag */
	private boolean error;
	
	/**
	 * Injects a reference to a valid logger
	 * 
	 * @param log a logger
	 */
	@Injected
	public void setLog(Log log) {
		this.log = log;
	}

	/**
	 * Injects a reference to a valid db manager
	 * 
	 * @param log a db manager
	 */	
	@Injected
	public void setDbManager(IDbManager manager) {
		this.manager = manager;
	}
	
	/**
	 * Creates a new instance of the job
	 * 
	 * @param cfg The datasource to use
	 * @param query The query to execute
	 */
	public SampleDbJob(DatasourceConfig cfg,String query) {
		this.query = query;
		this.cfg = cfg;
		rowCount = 0;
		error = false;
	}

	/* (non-Javadoc)
	 * @see it.battlehorse.rcp.tools.actors.IActorRunnable#getExecutionStatus()
	 */
	public IActorExecutionStatus getExecutionStatus() {
		return new SampleDbExecutionStatus(rowCount,error);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
	 */
	public void run(IProgressMonitor monitor) throws InvocationTargetException,
			InterruptedException {
		
		monitor.beginTask("Executing query... ", 2);
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			DataSource ds = manager.getDataSource(cfg);
			conn = ds.getConnection();
			ps = conn.prepareStatement(query);
			rs = ps.executeQuery();
			
			while (rs.next() && !monitor.isCanceled())
				rowCount++;
			
		}
		catch(SQLException sqle) {
			error = true;
			log.error("Error while executing query : " + sqle.getMessage(), sqle);
		}
		finally {
			try {
				if (rs != null) rs.close();
				if (ps != null) ps.close();
				if (conn != null) conn.close();
			}
			catch(SQLException sqle) {}
		}
		
		monitor.done();

	}

}
